import os
import django

# 设置Django环境
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'baojing.settings')
django.setup()

from django.core.management.base import BaseCommand
from projects.models import Webhook, Project
from django.conf import settings

class Command(BaseCommand):
    help = '列出系统中所有的Webhook URL'

    def add_arguments(self, parser):
        parser.add_argument(
            '--project-id',
            type=int,
            help='只显示指定项目的webhooks'
        )
        parser.add_argument(
            '--format',
            choices=['table', 'json', 'csv'],
            default='table',
            help='输出格式'
        )

    def handle(self, *args, **options):
        project_id = options.get('project_id')
        output_format = options.get('format')
        
        # 获取webhook列表
        if project_id:
            webhooks = Webhook.objects.filter(project_id=project_id)
            if not webhooks.exists():
                self.stdout.write(
                    self.style.ERROR(f'项目ID {project_id} 没有找到任何webhooks')
                )
                return
        else:
            webhooks = Webhook.objects.all().order_by('project__id', 'created_at')
        
        if not webhooks.exists():
            self.stdout.write(
                self.style.WARNING('系统中没有找到任何webhooks')
            )
            return
        
        # 获取站点域名
        site_domain = getattr(settings, 'SITE_DOMAIN', 'http://localhost:8000')
        
        if output_format == 'table':
            self.print_table(webhooks, site_domain)
        elif output_format == 'json':
            self.print_json(webhooks, site_domain)
        elif output_format == 'csv':
            self.print_csv(webhooks, site_domain)
    
    def print_table(self, webhooks, site_domain):
        """以表格形式打印webhook信息"""
        self.stdout.write(self.style.SUCCESS('=== 系统中所有Webhook URL列表 ==='))
        self.stdout.write('')
        
        # 打印表头
        header = f"{'项目':<20} {'Webhook名称':<25} {'完整URL':<60} {'状态':<8} {'创建时间'}"
        self.stdout.write(self.style.HTTP_INFO(header))
        self.stdout.write('-' * 120)
        
        for webhook in webhooks:
            # 生成完整的webhook URL
            project_id_str = str(webhook.project.id)
            webhook_id_str = str(webhook.id)
            full_url = f"{site_domain}/webhooks/{project_id_str}/{webhook_id_str}/receive/"
            
            # 格式化输出
            project_name = webhook.project.name[:18] + '..' if len(webhook.project.name) > 20 else webhook.project.name
            webhook_name = webhook.name[:23] + '..' if len(webhook.name) > 25 else webhook.name
            status = '激活' if webhook.is_active else '禁用'
            created_at = webhook.created_at.strftime('%Y-%m-%d %H:%M')
            
            line = f"{project_name:<20} {webhook_name:<25} {full_url:<60} {status:<8} {created_at}"
            
            if webhook.is_active:
                self.stdout.write(self.style.SUCCESS(line))
            else:
                self.stdout.write(line)
        
        self.stdout.write('')
        self.stdout.write(self.style.SUCCESS(f'总计: {webhooks.count()} 个webhooks'))
    
    def print_json(self, webhooks, site_domain):
        """以JSON格式打印webhook信息"""
        import json
        
        webhook_list = []
        for webhook in webhooks:
            project_id_str = str(webhook.project.id)
            webhook_id_str = str(webhook.id)
            full_url = f"{site_domain}/webhooks/{project_id_str}/{webhook_id_str}/receive/"
            
            webhook_list.append({
                'id': str(webhook.id),
                'name': webhook.name,
                'url': full_url,
                'project_id': webhook.project.id,
                'project_name': webhook.project.name,
                'is_active': webhook.is_active,
                'events': webhook.events,
                'created_at': webhook.created_at.isoformat(),
                'last_triggered_at': webhook.last_triggered_at.isoformat() if webhook.last_triggered_at else None
            })
        
        self.stdout.write(json.dumps(webhook_list, ensure_ascii=False, indent=2))
    
    def print_csv(self, webhooks, site_domain):
        """以CSV格式打印webhook信息"""
        import csv
        import sys
        
        writer = csv.writer(sys.stdout)
        writer.writerow(['项目ID', '项目名称', 'Webhook ID', 'Webhook名称', '完整URL', '状态', '事件', '创建时间'])
        
        for webhook in webhooks:
            project_id_str = str(webhook.project.id)
            webhook_id_str = str(webhook.id)
            full_url = f"{site_domain}/webhooks/{project_id_str}/{webhook_id_str}/receive/"
            
            writer.writerow([
                webhook.project.id,
                webhook.project.name,
                webhook.id,
                webhook.name,
                full_url,
                '激活' if webhook.is_active else '禁用',
                ','.join(webhook.events),
                webhook.created_at.strftime('%Y-%m-%d %H:%M:%S')
            ])